/**
 * 加密工具类
 *
 * @author liyang
 * @module server
 * @submodule rest
 * @class encryptUtils
 */
var crypto = require('crypto');
var secretKey = 'insteraction_1.0*';

module.exports = {
    /**
     * @method md5Encrypt
     * @param  {String} data 加密数据
     * @returns {String} 加密后的值
     */
    md5Encrypt: function (data) {
        var md5 = crypto.createHash('md5');
        md5.update(data);
        return md5.digest('hex');
    },
    /**
     * @method aes加密
     * @param  {String} data 加密数据
     * @param  {String} secretKey
     * @returns {String} 加密后的值
     */
    aesEncrypt: function (data, secretKey) {
        var iv = '';
        var clearEncoding = 'utf8';
        var cipherEncoding = 'base64';
        var cipherChunks = [];
        var cipher = crypto.createCipher('aes-128-ecb', secretKey, iv);
        cipher.setAutoPadding(true);
        cipherChunks.push(cipher.update(data, clearEncoding, cipherEncoding));
        cipherChunks.push(cipher.final(cipherEncoding));
        return cipherChunks.join('');
    },

    /**
     * @method aes解密
     * @param {String}  data 解密数据
     * @param  {String} secretKey
     * @returns {String} 解密后的值
     */
    aesDecrypt: function (data, secretKey) {
        /* var cipher = crypto.createDecipher('aes-128-ecb', secretKey);
        return cipher.update(data, 'hex', 'utf8') + cipher.final('utf8');*/

        var iv = '';
        var clearEncoding = 'utf8';
        var cipherEncoding = 'base64';
        var cipherChunks = [];
        var decipher = crypto.createDecipher('aes-128-ecb', secretKey, iv);
        decipher.setAutoPadding(true);
        cipherChunks.push(decipher.update(data, cipherEncoding, clearEncoding));
        cipherChunks.push(decipher.final(clearEncoding));
        return cipherChunks.join('');

    },
    getSecretKey: function () {
        return secretKey;
    },
    sha1: function (str) {
        var md5sum = crypto.createHash('sha1');
        md5sum.update(str);
        str = md5sum.digest('hex');
        return str;
    }
};
